package moe.bogos.douro.api.common.network;

import moe.bogos.douro.api.DouroAPI;
import moe.bogos.douro.api.common.network.message.UpdateCap;
import moe.bogos.douro.api.common.network.message.UseSkill;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.network.NetworkDirection;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.simple.SimpleChannel;

import static org.apache.http.params.CoreProtocolPNames.PROTOCOL_VERSION;

@Mod.EventBusSubscriber(modid = DouroAPI.MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class DouroAPINetworkHandler
{
    private static final SimpleChannel channel = NetworkRegistry.newSimpleChannel(
            new ResourceLocation(DouroAPI.MODID, "main"),
            () -> PROTOCOL_VERSION,
            PROTOCOL_VERSION::equals,
            PROTOCOL_VERSION::equals);
    
    private static int id = 0;
    
    public static void updateCap(PlayerEntity player, CompoundNBT tagCompound)
    {
        if (player instanceof ServerPlayerEntity)
            channel.sendTo(new UpdateCap(tagCompound),
                    ((ServerPlayerEntity) player).connection.connection, NetworkDirection.PLAY_TO_CLIENT);
    }
    
    public static void useSkill(String skillID)
    {
        channel.sendToServer(new UseSkill(skillID));
    }
    
    @SubscribeEvent
    public static void init(final FMLCommonSetupEvent event)
    {
        channel.registerMessage(id++,
                UpdateCap.class,
                UpdateCap::writeToPacket,
                UpdateCap::readFromPacket,
                UpdateCap::handle);
        channel.registerMessage(id++,
                UseSkill.class,
                UseSkill::writeToPacket,
                UseSkill::readFromPacket,
                UseSkill::handle);
    }
}
